package com.lpz.Controller;

import com.lpz.domian.User;
import com.sun.deploy.net.HttpResponse;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("user")
public class UserController {
    //通过返回字符串跳转页面
    @RequestMapping("/testString")
    public String testString(Model model){
        System.out.println(">>>>>>执行");
        User user=new User();
        user.setUsername("木木");
        user.setPassword("123");
        user.setAge(12);
        model.addAttribute("user",user);
        return "success";
    }
    //通过默认的方式进行跳转页面  请求转发是一次请求，不用写项目的名称
    @RequestMapping("/testvoid")
    public void testvoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);//手动写，那么就不会通过mvc的视图解析
        //response.sendRedirect(request.getContextPath()+"/index.jsp");
        //设置服务器的中文乱码问题
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //直接进行响应，拿到输出流。
        response.getWriter().print("你好");
        System.out.println("开始执行");
        return;//不让后面的再次执行
    }
    @RequestMapping("/modelandview")
    public ModelAndView testmodelandview(){
        ModelAndView mv=new ModelAndView();
        User user=new User();
        user.setAge(12);
        user.setUsername("mumu");
        user.setPassword("12222");
        //把user的对象存储到mv对象中，也会把user对象存入到request对象
        mv.addObject("user",user);
        //跳转到的页面字符串，通过视图解析器来定。
        mv.setViewName("success");
        return  mv;
    }
    //forward转发的使用
    @RequestMapping("/testfroward")
    public String testfroward(){
        //return "forward:/WEB-INF/pages/success.jsp";//固定写法forward:
        return "redirect:index.jsp";//固定写法redirect:
    }
    //Responsebody 通过异步的方式把数据写回去
    @RequestMapping("/testajax")
    public @ResponseBody User testajax(@RequestBody User user){
        System.out.println(">>>>>>>>>ajax执行>>>>>>>>>>"+user);//前端发送ajax请求，传的json字符串，后端把json字符串传到User对象
        //做响应，模拟查询数据库
        user.setAge(12);
        user.setUsername("dada");
        //做响应
        System.out.println(user.toString());
        return  user;
    }

}
